/**
 * <br>JAVACC DEMO 1.0<br>
 */
package com.apache.portal.weixin.action;

import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.client.InfoReleaseCoreCleint;
import com.apache.client.UctCoreClient;
import com.apache.client.UctProtoclClient;
import com.apache.jwt.PostHttps;
import com.apache.portal.common.oscache.OsCacheManager;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.rpc.common.LoadRpcService;
import com.apache.rpc.entity.InterfaceRegister;
import com.apache.tools.ConfigUtil;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.ToolsUtil;
import com.apache.uct.common.entity.User;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * description: 微信菜单的创建
 *
 * @author Hou DaYu 创建时间：上午10:56:37
 */
@SuppressWarnings("serial")
public class ReqWeixinAction extends BaseAction {

    /**
     * 创建微信菜单
     */
    public void execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String code = request.getParameter("code");
        log.info("code-->"+code);
        if (StrUtil.isNull(code)) {
            log.info("==============[OAuthServlet]获取网页授权code失败！");
            return;
        }
        Map<String, String> oa = getOAuthOpenId(code);
        if (null == oa) {
            log.info("==============[OAuthServlet]获取网页授权openId失败！");
            return;
        }
        String openId = oa.get("openid");
        log.info("openid="+openId);
        boolean mark = checkBind(request, openId);
        request.setAttribute("openid", openId);
        String send = request.getParameter("send");
        String params = request.getParameter("params");
        String pageUrl = "?userAgent=wx&tokenId=" + openId;
        if (StrUtil.isNotNull(params)) {
            params = params.replace("%3D", "=");
            params = params.replace("%2F", "/");
            params = params.replace("%26", "&");
            pageUrl += "&" + params;
        }
        send = send.replace("-", "/") + ".jsp";
        String forwardPageUrl = "/WEB-INF/pages/" + send + pageUrl;
        log.info("forwardPageUrl="+forwardPageUrl);
        request.getRequestDispatcher(forwardPageUrl).forward(request, response);
//        request.getRequestDispatcher("/index-weixin.jsp"+pageUrl).forward(request, response);
    }

    /**
     * description: 账号绑定执行
     */
    public void bindDo(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Map<String, Object> map = PortalPubFactory.getInstance().getMethodParams(request);
        ResultEntity entity = UctCoreClient
                .getUserByProperty("userEname", String.valueOf(map.get("userEname")));
        if (null == entity.getEntity()) {
            this.outputJson("{\"flag\":\"F\",\"msg\":\"not user\"}", response);
            return;
        }
        User user = (User) entity.getEntity();
        String pass = String.valueOf(map.get("userPass"));
        if (!user.getUserPass().equals(pass)) {
            this.outputJson("{\"flag\":\"F\",\"msg\":\"not pass error\"}", response);
            return;
        }
        map.put("userCname", user.getUserCname());
        map.put("userId", user.getUserId());
        map.put("createTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
        ResultMsg msg = InfoReleaseCoreCleint.getInstance().saveInfo(map);
        this.outputJson("{\"flag\":\"T\",\"msg\":\"ok\"}", response);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private boolean checkBind(HttpServletRequest request, String openid) {
        String sysPass = ConfigUtil.getInstance()
                .interfacePass();//ToolsUtil.getInstance().getValueByKey("push_to_interface_pass");
        Map map = new HashMap();
        map.put("sysPass", sysPass);
        map.put("openId", openid);
        map.put("sortCode", "weixin_user");
        Object obj = InfoReleaseCoreCleint.getInstance().selectSingle(map);
        if (null == obj) {
            return false;
        } else {
            Map weixinUser = (Map) obj;
            map.put("userEname", weixinUser.get("userEname"));
            ResultEntity entity = LoadRpcService.service()
                    .doServiceClient("uctService", "loginUserInfoSso", map, getUctRegister());
            if (null != entity.getEntity()) {
                OsCacheManager.getInstance().putLoginUser(openid, (LoginUser) entity.getEntity());
                request.getSession().setAttribute("loginUser", entity.getEntity());
            }
            return true;
        }
    }

    private Map<String, String> getOAuthOpenId(String code) {
        Map<String, String> oAuthInfo = null;
        String appid = ToolsUtil.getInstance().getValueByKey("ius_appid");
        String appsecret = ToolsUtil.getInstance().getValueByKey("ius_AppSecret");
//        String requestUrl ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret="+ appsecret + "&code=" + code + "&grant_type=authorization_code";
        String requestUrl= "https://api.weixin.qq.com/sns/oauth2/access_token";
        Map<String, String> paramsMap = new HashMap<String, String>();
        paramsMap.put("appid", appid);
        paramsMap.put("secret", appsecret);
        paramsMap.put("code", code);
        paramsMap.put("grant_type", "authorization_code");
        JSONObject jsonObject = null;
        try {
            String resultStr = sendHttpsByGet(requestUrl,paramsMap);
            jsonObject = JSONObject.fromObject(resultStr);
//                jsonObject = (JSONObject) HttpRequestTools.getInstance().httpRequest(requestUrl, "GET", null, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("result jsonObject="+jsonObject);

        //oAuthInfo是作者自己把那几个属性参数写在一个类里面了。
        // 如果请求成功
        if (null != jsonObject) {
            try {
                oAuthInfo = new HashMap<String, String>();
                oAuthInfo.put("accessToken", jsonObject.getString("access_token"));
                oAuthInfo.put("expiresIn", jsonObject.getInt("expires_in") + "");
                oAuthInfo.put("refreshToken", jsonObject.getString("refresh_token"));
                oAuthInfo.put("openid", jsonObject.getString("openid"));
                oAuthInfo.put("scope", jsonObject.getString("scope"));
            } catch (JSONException e) {
                e.printStackTrace();
                oAuthInfo = null;
                // 获取token失败
                System.out.println("网页授权获取openId失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + ";"+ jsonObject.getString("errmsg"));
            }
        }
        return oAuthInfo;
    }

    private InterfaceRegister getUctRegister() {
        return UctProtoclClient.getInstance()
                .getInterfaceRegister("uct", "uctServer_ip", "uctServer_port");
    }

    /**
     * get方式方式https请求
     * @param url
     * @param params
     * @return
     */
    private String sendHttpsByGet(String url,Map<String, String> params) {
        log.info("requestUrl="+url);
        log.info("requestParams="+params);
        String resultStr = "";
        if (params!=null && params.size()>0){
            NameValuePair[] paramsPair = new NameValuePair[params.size()];
            Iterator iterator = params.entrySet().iterator();
            int i =0;
            while(iterator.hasNext()){
                Map.Entry<String, String> entry= (Map.Entry<String, String>) iterator.next();
                paramsPair[i++] = new BasicNameValuePair(entry.getKey(), entry.getValue());
            }
            resultStr = PostHttps.newInstance().getHttpsForStl(url,paramsPair,"GET");
        }
        log.info("resultStr="+resultStr);
        return resultStr;
    }

}
